const gulp = require('gulp')
const del = require('del')

const deploySSH = require('./deploy-ssh') // 上传服务器相关配置
const deployConfig = require('./deploy-config') // 上传服务器相关配置
const zip = require('gulp-zip') // 压缩命令
const gulpSequence = require('gulp-sequence')
const MAIN = './'

const deployPath = '/home/nginx/data/ledgerPad/'

/* ----------------------清除build下的所有文件------------------------------------------- */
gulp.task('clean', function () {
  return del([MAIN + 'publish.zip']).then(function () {
    console.log('all cleaned...')
  })
})

/* ----------------------将dist目录下的文件打成dist包------------------------------------------------- */
gulp.task('zipFile', function () {
  // 优化为直接压缩指定文件更好一些
  return gulp
    .src(['dist/**'])
    .pipe(zip('publish.zip'))
    .pipe(gulp.dest('./'))
})
/* --------------------------发布到服务器--------------------------------------------------- */
gulp.task('deploy', function () {
  var config = deployConfig.production.test // pro_env为环境变量 test(测试)|pre(预发布)|www(正式环境)

  return gulp
    .src('publish.zip', {
      base: './'
    })
    .pipe(
      deploySSH({
        sshConfig: config.sshConfig,
        dest: deployPath + 'publish.zip',
        logPath: 'deploy',
        shell: [
          // 'mkdir ' + config.deployPath,
          'cd ' + deployPath,
          'shopt -s extglob',
          'rm -rf !(logs|publish.zip)',
          // 'tar --no-same-owner -zxf publish.tar.gz',

          'unzip publish.zip',
          'chmod -R 755 ' + deployPath,
          // 'mv dist/** .',
          'rm -rf publish.zip',
          // 压缩gzip压缩
          // 'gzip -9rv ./images',
          'touch ' + deployPath
        ]
      })
    )
})

gulp.task('deployWWW', function () {
  var config = deployConfig.production.www // pro_env为环境变量 test(测试)|pre(预发布)|www(正式环境)
  return gulp
    .src('publish.zip', {
      base: './'
    })
    .pipe(
      deploySSH({
        sshConfig: config.sshConfig,
        dest: deployPath + 'publish.zip',
        logPath: 'deploy',
        shell: [
          // 'mkdir ' + config.deployPath,
          'cd ' + deployPath,
          'shopt -s extglob',
          'rm -rf !(logs|publish.zip)',
          // 'tar --no-same-owner -zxf publish.tar.gz',

          'unzip publish.zip',
          'chmod -R 755 ' + deployPath,
          // 'mv dist/** .',
          'rm -rf publish.zip',
          // 压缩gzip压缩
          // 'gzip -9rv ./images',
          'touch ' + deployPath
        ]
      })
    )
})

/* ---------------------发布---------------------------------------------------------- */
gulp.task('publish', function () {
  // gulp 任务序列  忽略任务,'copyFile'
  gulpSequence('clean', 'zipFile', 'deploy', function () {
    console.log('***** Deploy WWW Finished！！！！')
  })
})
gulp.task('publishwww', function () {
  // gulp 任务序列  忽略任务,'copyFile'
  gulpSequence('clean', 'zipFile', 'deployWWW', function () {
    console.log('***** Deploy WWW Finished！！！！')
  })
})
